package com.virgo.web.handler;

import com.virgo.common.entity.IResponse;
import com.virgo.common.exception.IApplicationException;
import com.virgo.common.exception.INoLoginException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.Arrays;
import java.util.Objects;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	private IResponse<String> exceptionHandler(HttpServletRequest request, Exception e){
		log.error("引发错误的类" + e.getClass().getName());
		log.error(e.getMessage());
		log.error(Arrays.toString(e.getStackTrace()));
		return IResponse.fail("网络错误,请重试");
	}

	@ExceptionHandler(value = INoLoginException.class)
	@ResponseBody
	private IResponse<String> noLoginExceptionHandler(HttpServletRequest request,Exception e){
		return IResponse.logout();
	}

	@ExceptionHandler(value = IApplicationException.class)
	@ResponseBody
	private IResponse<String> applicationExceptionHandler(HttpServletRequest request,Exception e){
		return IResponse.fail(e.getMessage(),2002);
	}

	@ExceptionHandler(value = NullPointerException.class)
	@ResponseBody
	private IResponse<String> NullPointerExceptionHandler(HttpServletRequest request,Exception e){
		log.error(Arrays.toString(e.getStackTrace()));
		return IResponse.fail("网络错误,请重试2",2002);
	}

	@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
	@ResponseBody
	private IResponse<String> methodNotSupportedExceptionHandler(HttpServletRequest request,HttpRequestMethodNotSupportedException e){
		return IResponse.fail("不支持当前请求方式",2003);
	}

	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	private IResponse<String> BindExceptionHandler(HttpServletRequest request,BindException e){
		BindingResult bindingResult = e.getBindingResult();
		return IResponse.fail(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage(),2002);
	}

	@ExceptionHandler(value = NoResourceFoundException.class)
	@ResponseBody
	private IResponse<String> noResourceFoundExceptionHandler(HttpServletRequest request, Exception e){
		return IResponse.fail("资源不存在");
	}

}
